// src/services/useDataActions.js
// 封装表单提交
import {ElMessage, ElMessageBox} from "element-plus";

// 定义通用的 API 接口结构
const defaultApi = {
  add: (data) => Promise.resolve(data),
  update: (id, data) => Promise.resolve(data),
  delete: (id) => Promise.resolve(id),
};


export function useDataActions({ api = defaultApi, onActionSuccess = () => {}, messages = {} }) {
  // 验证 api 对象是否包含必要的方法
  const mergedApi = { ...defaultApi, ...api }

  // 检查是否有未定义的方法
  Object.keys(mergedApi).forEach(key => {
    if (!defaultApi.hasOwnProperty(key)) {
      console.warn(`API 警告: 方法 '${key}' 未在 defaultApi 中定义，但已被使用`)
    }
  })

  const defaultMessages = {
    add: '新增成功',
    update: '编辑成功',
    delete: '删除成功',
    updateField: '更新成功',
    error: '操作失败'
  }

  const finalMessages = { ...defaultMessages, ...messages }

  async function handleFormSubmit(formData) {
    let isEditMode = !!formData.id;
    let apiCall = isEditMode ? api.update : api.add;
    let successMessageKey = isEditMode ? 'update' : 'add';

    try {
      const res = await apiCall(formData);
      if (res.code === 0) {
        ElMessage.success(finalMessages[successMessageKey]);
        onActionSuccess();
      } else {
        ElMessage.error(res.message);
      }
    } catch (error) {
      console.error('提交失败:', error);
      ElMessage.error(finalMessages.error || '操作失败，请稍后再试');
    }
  }


  async function handleDelete(id) {
    try {
      await ElMessageBox.confirm('确定要删除该项吗？', '提示', { type: 'warning' })
      const res = await api.delete(id)
      let successMessageKey = "delete";
      if (res.code === 0) {
        ElMessage.success(finalMessages[successMessageKey]);
        onActionSuccess()
      } else {
        ElMessage.error(res.message);
      }
    } catch (error) {
      console.error('删除失败:', error)
    }
  }

  async function handleFieldUpdate(data) {
    try {
      const params = { ...data }
      delete params.children
      const res = await api.update(params)
      let successMessageKey = "update";
      if (res.code === 0) {
        ElMessage.success(finalMessages[successMessageKey]);
        onActionSuccess()
      } else {
        ElMessage.error(res.message);
      }
    } catch (error) {
      console.error('更新失败:', error)
      ElMessage.error(finalMessages.error)
    }
  }

  return {
    handleFormSubmit,
    handleDelete,
    handleFieldUpdate
  }
}